//
//  UITextView+emoticons.swift
//  FaceKeyBoard
//
//  Created by cmh on 15/9/13.
//  Copyright © 2015年 cmh. All rights reserved.
//

import UIKit

extension UITextView {

    // 出入表情符号
    func insertEmoticon(emoticon: Emoticon) {
        
        // 1.空表情
        if emoticon.isEmpty {
            return
        }
        
        // 2.删除按钮
        if emoticon.isRemove {
            deleteBackward()
            return
        }
        
        // 3.emoji
        if emoticon.emoji != nil {
            replaceRange(selectedTextRange!, withText: emoticon.emoji!)
            return
        }
        
        // 4.表情图片
        // 4.表情图片的文本
        let imageText = EmoticonAttachment.emoticonAttributeText(emoticon, font: font!)
        
        // 从textView中取出属性文本
        let strM = NSMutableAttributedString(attributedString: attributedText)
        
        // 插入图片文字
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        
        // 重新设置textView的内容
        // 记录光标的位置
        let range = selectedRange
        
        // 设置内容
        attributedText = strM
        
        // 设光标位置
        selectedRange = NSRange(location: range.location + 1, length: 0)
        
    }
    
    // textView中的所有文本
    var tectViewAttributedText: String {
        let attrText = attributedText
        
        var strM = String()
        
        attrText.enumerateAttributesInRange(NSRange(location: 0, length: attrText.length), options: []) { (dict, range, _) -> Void in
            
            // 含NSAttachment，说明是图片
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment
            {
                strM += attachment.chs
            }
            else // 文本内容
            {
                let str = (attrText.string as NSString).substringWithRange(range)
                strM += str
            }
        }
        
        print("最终结果\(strM)")
        
        return strM

    }

}


